﻿using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LicenseApp.Client;

namespace LicenseApp.ClientTool;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private bool _isMonitoring = false;

    public MainWindow()
    {
        InitializeComponent();
        InitializeApplication();
    }

    private void InitializeApplication()
    {
        // 设置自定义通知器（使用窗口通知）
        LicenseManager.SetNotifier(new CustomWindowNotifier());

        // 初始化界面状态
        UpdateUI();

        // 初始化机器码测试区域
        InitializeMachineCodeTest();

        // 添加初始日志
        AddLog("应用程序启动");

        // 检查公钥状态
        CheckPublicKeyStatus();

        // 检查是否已有授权
        RefreshStatus();
    }

    private void UpdateUI()
    {
        btnStopMonitoring.IsEnabled = _isMonitoring;
        btnStartMonitoring.IsEnabled = !_isMonitoring;
    }

    private void AddLog(string message)
    {
        var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        var logEntry = $"[{timestamp}] {message}";

        Dispatcher.BeginInvoke(() =>
        {
            txtLog.AppendText(logEntry + Environment.NewLine);
            txtLog.ScrollToEnd();
        });
    }

    private void RefreshStatus()
    {
        try
        {
            var statusInfo = LicenseManager.GetCurrentStatus();

            // 更新状态指示器
            UpdateStatusIndicator(statusInfo.Status);

            // 更新状态文本
            txtStatus.Text = GetStatusText(statusInfo.Status);

            // 更新详细信息
            UpdateStatusDetails(statusInfo);

            // 更新状态栏
            var licenseInfo = LicenseManager.GetLicenseInfo();
            if (licenseInfo != null)
            {
                txtStatusBar.Text = $"授权状态: {GetStatusText(statusInfo.Status)} | AGV: {licenseInfo.AgvCount}台 | 最后检查: {DateTime.Now:HH:mm:ss}";
            }
            else
            {
                txtStatusBar.Text = $"状态: {GetStatusText(statusInfo.Status)} | 最后检查: {DateTime.Now:HH:mm:ss}";
            }

            AddLog($"状态检查: {GetStatusText(statusInfo.Status)}");
        }
        catch (Exception ex)
        {
            AddLog($"状态检查失败: {ex.Message}");
            txtStatus.Text = "检查失败";
            statusIndicator.Fill = Brushes.Red;
        }
    }

    private void UpdateStatusIndicator(LicenseStatus status)
    {
        statusIndicator.Fill = status switch
        {
            LicenseStatus.Valid => Brushes.Green,
            LicenseStatus.ExpiringSoon => Brushes.Orange,
            LicenseStatus.ExpiredGracePeriod => Brushes.Yellow,
            LicenseStatus.Expired => Brushes.Red,
            _ => Brushes.Gray
        };
    }

    private string GetStatusText(LicenseStatus status)
    {
        return status switch
        {
            LicenseStatus.Valid => "授权有效",
            LicenseStatus.ExpiringSoon => "即将到期",
            LicenseStatus.ExpiredGracePeriod => "宽限期内",
            LicenseStatus.Expired => "已过期",
            _ => "未知状态"
        };
    }

    private void UpdateStatusDetails(LicenseStatusInfo statusInfo)
    {
        try
        {
            // 获取授权信息
            var licenseInfo = LicenseManager.GetLicenseInfo();

            if (licenseInfo != null)
            {
                // 更新基本信息
                txtStartDate.Text = licenseInfo.StartDate.ToString("yyyy-MM-dd");
                txtEndDate.Text = licenseInfo.EndDate.ToString("yyyy-MM-dd");
                txtDays.Text = $"{licenseInfo.Days} 天";
                txtAgvCount.Text = $"{licenseInfo.AgvCount} 台";

                // 更新机器码信息
                UpdateMachineCodeInfo(licenseInfo);
            }
            else
            {
                // 清空信息
                txtStartDate.Text = "-";
                txtEndDate.Text = "-";
                txtDays.Text = "-";
                txtAgvCount.Text = "-";

                // 清空机器码信息
                txtBoundMachineCode.Text = "-";
                txtCurrentMachineCode.Text = MachineCodeGenerator.GenerateMachineCode();
            }

            // 更新状态消息
            var statusMessage = new StringBuilder();
            statusMessage.Append(statusInfo.Message);

            if (statusInfo.RemainingDays >= 0)
            {
                statusMessage.Append($" (剩余 {statusInfo.RemainingDays} 天)");
            }

            if (statusInfo.IsGracePeriod && statusInfo.GracePeriod != null)
            {
                var grace = statusInfo.GracePeriod;
                var remainingHours = (int)grace.RemainingGraceTime.TotalHours;
                statusMessage.Append($" - 宽限期剩余 {remainingHours} 小时");
            }

            txtStatusMessage.Text = statusMessage.ToString();

            // 更新检查时间
            txtLastCheckTime.Text = statusInfo.CheckTime.ToString("yyyy-MM-dd HH:mm:ss");
        }
        catch (Exception ex)
        {
            // 出错时显示错误信息
            txtStatusMessage.Text = $"更新状态信息时出错: {ex.Message}";
            txtLastCheckTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }

    private void CheckPublicKeyStatus()
    {
        try
        {
            // 应用程序路径获取 - 按要求实现
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            string publicKeyPath = System.IO.Path.Combine(assemblyDirPath, "public.xml");

            if (System.IO.File.Exists(publicKeyPath))
            {
                var publicKeyContent = System.IO.File.ReadAllText(publicKeyPath);

                // 验证公钥格式
                if (IsValidPublicKey(publicKeyContent))
                {
                    txtPublicKeyStatus.Text = "✅ 已导入";
                    txtPublicKeyStatus.Foreground = Brushes.Green;
                    txtPublicKeyInfo.Text = $"公钥文件: {publicKeyPath}\n文件大小: {new System.IO.FileInfo(publicKeyPath).Length} 字节";

                    // 初始化授权系统
                    LicenseManager.Initialize(publicKeyContent);
                    AddLog("公钥已加载，授权系统初始化完成");
                }
                else
                {
                    txtPublicKeyStatus.Text = "❌ 格式错误";
                    txtPublicKeyStatus.Foreground = Brushes.Red;
                    txtPublicKeyInfo.Text = "公钥文件格式不正确，请重新导入";
                    AddLog("公钥文件格式错误");
                }
            }
            else
            {
                txtPublicKeyStatus.Text = "❌ 未导入";
                txtPublicKeyStatus.Foreground = Brushes.Red;
                txtPublicKeyInfo.Text = $"请导入公钥文件到: {publicKeyPath}";
                AddLog("未找到公钥文件，请先导入公钥");
            }
        }
        catch (Exception ex)
        {
            txtPublicKeyStatus.Text = "❌ 检查失败";
            txtPublicKeyStatus.Foreground = Brushes.Red;
            txtPublicKeyInfo.Text = $"检查公钥时发生错误: {ex.Message}";
            AddLog($"公钥检查失败: {ex.Message}");
        }
    }

    private bool IsValidPublicKey(string publicKeyXml)
    {
        try
        {
            // 尝试加载RSA公钥来验证格式
            using var rsa = System.Security.Cryptography.RSA.Create();
            rsa.FromXmlString(publicKeyXml);
            return true;
        }
        catch
        {
            return false;
        }
    }

    // === 事件处理方法 ===

    private void BtnImportPublicKey_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // 打开文件对话框
            var openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Title = "选择公钥文件",
                Filter = "XML文件 (*.xml)|*.xml|所有文件 (*.*)|*.*",
                DefaultExt = ".xml"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                var sourceFile = openFileDialog.FileName;

                // 读取公钥内容
                var publicKeyContent = System.IO.File.ReadAllText(sourceFile);

                // 验证公钥格式
                if (!IsValidPublicKey(publicKeyContent))
                {
                    MessageBox.Show("选择的文件不是有效的RSA公钥文件", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 获取目标路径
                string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
                string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
                string targetPath = System.IO.Path.Combine(assemblyDirPath, "public.xml");

                // 如果目标文件已存在，询问是否覆盖
                if (System.IO.File.Exists(targetPath))
                {
                    var result = MessageBox.Show("公钥文件已存在，是否覆盖？", "确认",
                        MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                        return;
                }

                // 复制文件
                System.IO.File.Copy(sourceFile, targetPath, true);

                // 初始化授权系统
                bool initResult = LicenseManager.Initialize(publicKeyContent);

                if (initResult)
                {
                    AddLog($"公钥导入成功: {sourceFile} -> {targetPath}");
                    LicenseManager.ShowNotification("公钥导入成功", LicenseStatus.Valid);

                    // 刷新公钥状态
                    CheckPublicKeyStatus();

                    // 刷新授权状态
                    RefreshStatus();
                }
                else
                {
                    AddLog("公钥导入失败：初始化授权系统失败");
                    MessageBox.Show("公钥导入失败，初始化授权系统时出错", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        catch (Exception ex)
        {
            AddLog($"导入公钥异常: {ex.Message}");
            MessageBox.Show($"导入公钥时发生错误: {ex.Message}", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnRegister_Click(object sender, RoutedEventArgs e)
    {
        var licenseCode = txtLicenseCode.Text.Trim();

        if (string.IsNullOrEmpty(licenseCode))
        {
            MessageBox.Show("请输入授权码", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        // 检查公钥状态
        if (txtPublicKeyStatus.Text.Contains("未导入") || txtPublicKeyStatus.Text.Contains("格式错误"))
        {
            var result = MessageBox.Show("尚未导入有效的公钥文件，无法验证授权码。\n\n是否现在导入公钥？",
                "需要公钥", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                BtnImportPublicKey_Click(sender, e);
                return;
            }
            else
            {
                return;
            }
        }

        try
        {
            // 🎯 先检查注册风险
            var riskCheck = LicenseApp.Client.LicenseValidator.GetRegistrationRisk(licenseCode);

            if (!riskCheck.CanRegister)
            {
                // 不能注册（如重复注册相同有效授权）
                AddLog($"注册被拒绝: {riskCheck.Message}");
                MessageBox.Show(riskCheck.Message, "无法注册", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (riskCheck.RequiresConfirmation)
            {
                // 需要用户确认风险（如替换当前有效授权）
                AddLog($"需要确认风险: {riskCheck.RiskLevel}");

                var confirmResult = MessageBox.Show(
                    riskCheck.Message + "\n\n是否确认继续注册？",
                    "风险确认",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning,
                    MessageBoxResult.No);

                if (confirmResult != MessageBoxResult.Yes)
                {
                    AddLog("用户取消注册");
                    return; // 用户取消注册
                }

                // 用户确认后，使用带确认参数的注册方法
                bool success = LicenseApp.Client.LicenseValidator.RegisterLicense(licenseCode, true);
                HandleRegistrationResult(success, licenseCode);
            }
            else
            {
                // 安全注册，直接执行
                bool success = LicenseManager.RegisterLicense(licenseCode);
                HandleRegistrationResult(success, licenseCode);
            }
        }
        catch (Exception ex)
        {
            AddLog($"授权码注册异常: {ex.Message}");
            MessageBox.Show($"注册过程中发生错误: {ex.Message}", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 处理注册结果
    /// </summary>
    private void HandleRegistrationResult(bool success, string licenseCode)
    {
        if (success)
        {
            AddLog("授权码注册成功");
            LicenseManager.ShowNotification("授权码注册成功", LicenseStatus.Valid);

            // 清空输入框
            txtLicenseCode.Clear();

            // 刷新状态
            RefreshStatus();
        }
        else
        {
            // 🎯 获取详细的失败原因
            string detailedReason = GetRegistrationFailureReason(licenseCode);
            AddLog($"授权码注册失败：{detailedReason}");

            MessageBox.Show(detailedReason, "注册失败", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 获取注册失败的详细原因
    /// </summary>
    private string GetRegistrationFailureReason(string licenseCode)
    {
        try
        {
            // 1. 检查授权码格式和签名
            var licenseInfo = LicenseApp.Client.LicenseValidator.ValidateLicenseCode(licenseCode);
            if (licenseInfo == null)
            {
                return "授权码格式错误或签名验证失败\n\n" +
                       "可能的原因：\n" +
                       "• 授权码格式不正确\n" +
                       "• 公钥与授权码不匹配\n" +
                       "• 授权码已损坏";
            }

            // 2. 检查时间和使用天数验证
            var validation = LicenseApp.Client.UnifiedLicenseGuard.ValidateLicense(licenseInfo);
            if (!validation.IsValid)
            {
                return $"授权验证失败：{validation.Message}";
            }

            // 3. 如果验证都通过了，说明是保存失败
            return "授权码保存失败\n\n" +
                   "可能的原因：\n" +
                   "• 磁盘空间不足\n" +
                   "• 文件权限不足\n" +
                   "• 系统资源不足";
        }
        catch (Exception ex)
        {
            return $"注册过程中发生异常：{ex.Message}";
        }
    }

    private void BtnClear_Click(object sender, RoutedEventArgs e)
    {
        var result = MessageBox.Show("确定要清除当前授权吗？", "确认",
            MessageBoxButton.YesNo, MessageBoxImage.Question);

        if (result == MessageBoxResult.Yes)
        {
            try
            {
                bool success = LicenseManager.ClearLicense();

                if (success)
                {
                    AddLog("授权已清除");
                    LicenseManager.ShowNotification("授权已清除", LicenseStatus.Expired);
                    RefreshStatus();
                }
                else
                {
                    AddLog("清除授权失败");
                    MessageBox.Show("清除授权失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                AddLog($"清除授权异常: {ex.Message}");
                MessageBox.Show($"清除过程中发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private void BtnRefresh_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatus();
    }

    private void BtnStartMonitoring_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            bool success = LicenseManager.StartLicenseMonitoring(OnLicenseStatusChanged, TimeSpan.FromMinutes(1));

            if (success)
            {
                _isMonitoring = true;
                UpdateUI();
                AddLog("授权监控已启动");
                LicenseManager.ShowNotification("授权监控已启动", LicenseStatus.Valid);
            }
            else
            {
                AddLog("启动监控失败");
                MessageBox.Show("启动监控失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        catch (Exception ex)
        {
            AddLog($"启动监控异常: {ex.Message}");
            MessageBox.Show($"启动监控时发生错误: {ex.Message}", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnStopMonitoring_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            LicenseManager.StopMonitoring();
            _isMonitoring = false;
            UpdateUI();
            AddLog("授权监控已停止");
        }
        catch (Exception ex)
        {
            AddLog($"停止监控异常: {ex.Message}");
        }
    }

    private void BtnClearLog_Click(object sender, RoutedEventArgs e)
    {
        txtLog.Clear();
        AddLog("日志已清空");
    }

    private void OnLicenseStatusChanged(LicenseStatusInfo statusInfo)
    {
        Dispatcher.BeginInvoke(() =>
        {
            // 更新界面状态
            UpdateStatusIndicator(statusInfo.Status);
            txtStatus.Text = GetStatusText(statusInfo.Status);
            UpdateStatusDetails(statusInfo);

            // 记录日志
            AddLog($"状态变化: {GetStatusText(statusInfo.Status)} - {statusInfo.Message}");

            // 根据状态显示通知
            switch (statusInfo.Status)
            {
                case LicenseStatus.ExpiringSoon:
                    LicenseManager.ShowNotification($"授权即将到期，剩余{statusInfo.RemainingDays}天",
                        LicenseStatus.ExpiringSoon);
                    break;

                case LicenseStatus.ExpiredGracePeriod:
                    if (statusInfo.GracePeriod != null)
                    {
                        var hours = (int)statusInfo.GracePeriod.RemainingGraceTime.TotalHours;
                        LicenseManager.ShowNotification($"授权已过期，宽限期剩余{hours}小时",
                            LicenseStatus.ExpiredGracePeriod);
                    }
                    break;

                case LicenseStatus.Expired:
                    LicenseManager.ShowNotification("授权已过期，请联系供应商续期",
                        LicenseStatus.Expired);
                    break;
            }
        });
    }

    /// <summary>
    /// 更新机器码信息
    /// </summary>
    private void UpdateMachineCodeInfo(LicenseInfo licenseInfo)
    {
        try
        {
            // 显示绑定的机器码
            if (!string.IsNullOrEmpty(licenseInfo.MachineCode))
            {
                txtBoundMachineCode.Text = licenseInfo.MachineCode;
                txtBoundMachineCode.Foreground = Brushes.Black;
            }
            else
            {
                txtBoundMachineCode.Text = "未绑定机器";
                txtBoundMachineCode.Foreground = Brushes.Gray;
            }

            // 显示当前机器码
            var currentMachineCode = MachineCodeGenerator.GenerateMachineCode();
            txtCurrentMachineCode.Text = currentMachineCode;

            // 检查机器码是否匹配
            if (!string.IsNullOrEmpty(licenseInfo.MachineCode))
            {
                if (licenseInfo.MachineCode == currentMachineCode)
                {
                    txtCurrentMachineCode.Foreground = Brushes.Green;
                }
                else
                {
                    txtCurrentMachineCode.Foreground = Brushes.Red;
                }
            }
            else
            {
                txtCurrentMachineCode.Foreground = Brushes.Black;
            }
        }
        catch (Exception ex)
        {
            txtBoundMachineCode.Text = "获取失败";
            txtCurrentMachineCode.Text = "获取失败";
            AddLog($"更新机器码信息失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 显示机器码详细信息
    /// </summary>
    private void BtnShowMachineCodeDetails_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var details = MachineCodeGenerator.GetMachineCodeComponents();
            MessageBox.Show(details, "机器码详细信息", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"获取机器码详细信息失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    #region 机器码测试功能

    /// <summary>
    /// 初始化机器码测试区域
    /// </summary>
    private void InitializeMachineCodeTest()
    {
        try
        {
            // 自动生成并显示当前机器码
            GenerateAndDisplayMachineCode();
        }
        catch (Exception ex)
        {
            AddLog($"初始化机器码测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 生成机器码按钮点击事件
    /// </summary>
    private void BtnGenerateMachineCode_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            GenerateAndDisplayMachineCode();
            AddLog("机器码生成成功");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"生成机器码失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
            AddLog($"生成机器码失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 复制机器码按钮点击事件
    /// </summary>
    private void BtnCopyMachineCode_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(txtTestMachineCode.Text))
            {
                Clipboard.SetText(txtTestMachineCode.Text);
                MessageBox.Show("机器码已复制到剪贴板！\n\n可以粘贴到生产工具中生成绑定授权码。",
                              "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
                AddLog("机器码已复制到剪贴板");
            }
            else
            {
                MessageBox.Show("没有可复制的机器码", "提示",
                              MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"复制机器码失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 显示机器码详细组件信息
    /// </summary>
    private void BtnShowMachineCodeInfo_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var details = MachineCodeGenerator.GetMachineCodeComponents();
            MessageBox.Show(details, "机器码详细组件信息", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"获取机器码详细信息失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 测试机器码验证功能
    /// </summary>
    private void BtnTestMachineCodeValidation_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var currentMachineCode = MachineCodeGenerator.GenerateMachineCode();

            // 测试自我验证
            var isValid = MachineCodeGenerator.ValidateMachineCode(currentMachineCode, tolerance: 1);

            var testResult = $"机器码验证测试结果：\n\n" +
                           $"当前机器码: {currentMachineCode}\n" +
                           $"自我验证结果: {(isValid ? "✅ 通过" : "❌ 失败")}\n\n" +
                           $"容错级别: 1 (允许1个组件变化)\n" +
                           $"验证状态: {(isValid ? "正常" : "异常")}";

            MessageBox.Show(testResult, "机器码验证测试",
                          MessageBoxButton.OK,
                          isValid ? MessageBoxImage.Information : MessageBoxImage.Warning);

            AddLog($"机器码验证测试: {(isValid ? "通过" : "失败")}");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"机器码验证测试失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
            AddLog($"机器码验证测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 生成并显示机器码
    /// </summary>
    private void GenerateAndDisplayMachineCode()
    {
        var machineCode = MachineCodeGenerator.GenerateMachineCode();
        txtTestMachineCode.Text = machineCode;

        // 更新工具提示
        txtTestMachineCode.ToolTip = $"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n" +
                                   $"机器码: {machineCode}\n" +
                                   $"点击'详细组件信息'查看生成详情";
    }

    #endregion

    #region 初始化测试功能

    /// <summary>
    /// 测试初始化按钮点击事件
    /// </summary>
    private void BtnTestInitialization_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            AddLog("=== 开始测试初始化流程 ===");

            // 测试1: 正常初始化流程
            TestNormalInitialization();

            // 测试2: 无授权文件的初始化
            TestInitializationWithoutLicense();

            // 测试3: 授权验证失败的初始化
            TestInitializationWithInvalidLicense();

            // 测试4: 初始化流程的完整性
            TestInitializationCompleteness();

            AddLog("=== 初始化流程测试完成 ===");

            MessageBox.Show("初始化流程测试完成！请查看日志了解详细结果。", "测试完成",
                          MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            AddLog($"初始化流程测试失败: {ex.Message}");
            MessageBox.Show($"初始化流程测试失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 测试正常初始化流程
    /// </summary>
    private void TestNormalInitialization()
    {
        try
        {
            AddLog("测试1: 正常初始化流程");

            // 获取当前授权状态
            var currentStatus = LicenseManager.GetCurrentStatus();
            AddLog($"📊 当前授权状态: {currentStatus.Message}");

            // 执行初始化
            AddLog("🔄 执行初始化...");
            var result = LicenseHelper.InitializeLicense(
                parentWindow: this,
                autoStartMonitoring: false, // 避免重复启动监控
                onStatusChanged: null,
                showErrorDialog: true // 显示错误对话框
            );

            AddLog($"   初始化结果: {(result.Success ? "✅ 成功" : "❌ 失败")}");
            AddLog($"   消息: {result.Message}");
            AddLog($"   需要注册: {result.NeedsLicenseRegistration}");
            AddLog($"   警告数量: {result.Warnings.Count}");

            if (result.Warnings.Count > 0)
            {
                foreach (var warning in result.Warnings)
                {
                    AddLog($"   ⚠️ 警告: {warning}");
                }
            }

            if (result.LicenseStatus != null)
            {
                AddLog($"   授权状态: {result.LicenseStatus.Status}");
                AddLog($"   状态消息: {result.LicenseStatus.Message}");
            }

            // 验证初始化后的状态
            var afterStatus = LicenseManager.GetCurrentStatus();
            AddLog($"📊 初始化后状态: {afterStatus.Message}");

            AddLog("✅ 正常初始化流程测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 正常初始化流程测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试无授权文件的初始化
    /// </summary>
    private void TestInitializationWithoutLicense()
    {
        try
        {
            AddLog("测试2: 无授权文件的初始化");

            // 备份当前授权文件（如果存在）
            var assemblyDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? "";
            var licenseFile = System.IO.Path.Combine(assemblyDir, "System.ZhyLsHK.dll");
            var backupFile = licenseFile + ".backup";

            bool hasLicenseFile = File.Exists(licenseFile);
            if (hasLicenseFile)
            {
                AddLog("📋 备份现有授权文件");
                File.Copy(licenseFile, backupFile, true);
                File.Delete(licenseFile);
            }

            try
            {
                AddLog("🔄 在无授权文件情况下执行初始化（显示对话框）...");
                var result = LicenseHelper.InitializeLicense(
                    parentWindow: this,
                    autoStartMonitoring: false,
                    onStatusChanged: null,
                    showErrorDialog: true
                );

                AddLog($"   初始化结果: {(result.Success ? "✅ 成功" : "❌ 失败")}");
                AddLog($"   消息: {result.Message}");
                AddLog($"   需要注册: {result.NeedsLicenseRegistration}");

                // 测试不显示对话框的情况
                AddLog("🔄 在无授权文件情况下执行初始化（不显示对话框）...");
                var result2 = LicenseHelper.InitializeLicense(
                    parentWindow: this,
                    autoStartMonitoring: false,
                    onStatusChanged: null,
                    showErrorDialog: false
                );

                AddLog($"   初始化结果: {(result2.Success ? "✅ 成功" : "❌ 失败")}");
                AddLog($"   消息: {result2.Message}");
                AddLog($"   需要注册: {result2.NeedsLicenseRegistration}");

                // 验证关键行为：即使无授权文件，初始化也应该完成
                if (result2.NeedsLicenseRegistration)
                {
                    AddLog("✅ 正确识别需要注册授权");
                }

                // 对比两次初始化的结果
                if (result.Success == result2.Success && result.Message == result2.Message)
                {
                    AddLog("✅ showErrorDialog 参数不影响初始化结果，只影响对话框显示");
                }
                else
                {
                    AddLog("⚠️ showErrorDialog 参数可能影响了初始化结果");
                }

                // 验证监控等功能是否正常初始化
                var status = LicenseManager.GetCurrentStatus();
                AddLog($"📊 无授权文件时的状态: {status.Message}");

                AddLog("✅ 无授权文件初始化测试完成");
            }
            finally
            {
                // 恢复授权文件
                if (hasLicenseFile && File.Exists(backupFile))
                {
                    AddLog("📋 恢复授权文件");
                    File.Copy(backupFile, licenseFile, true);
                    File.Delete(backupFile);
                }
            }
        }
        catch (Exception ex)
        {
            AddLog($"❌ 无授权文件初始化测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试授权验证失败的初始化
    /// </summary>
    private void TestInitializationWithInvalidLicense()
    {
        try
        {
            AddLog("测试3: 授权验证失败的初始化");

            // 这个测试主要验证当授权过期、时间回拨等情况下，初始化是否正常完成
            AddLog("🔍 检查当前授权验证状态");

            var isValid = LicenseManager.IsLicenseValid();
            var status = LicenseManager.GetCurrentStatus();

            AddLog($"   当前授权有效: {isValid}");
            AddLog($"   当前状态: {status.Message}");

            if (!isValid)
            {
                AddLog("📋 当前授权无效，测试初始化行为");

                var result = LicenseHelper.InitializeLicense(
                    parentWindow: this,
                    autoStartMonitoring: false,
                    onStatusChanged: null
                );

                AddLog($"   初始化结果: {(result.Success ? "✅ 成功" : "❌ 失败")}");
                AddLog($"   消息: {result.Message}");
                AddLog($"   需要注册: {result.NeedsLicenseRegistration}");

                // 验证关键行为：即使授权验证失败，初始化也应该完成
                AddLog("✅ 验证授权验证失败时初始化仍能完成");
            }
            else
            {
                AddLog("📋 当前授权有效，跳过此测试");
                AddLog("💡 提示：可以通过修改系统时间或删除授权文件来测试此场景");
            }

            AddLog("✅ 授权验证失败初始化测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 授权验证失败初始化测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试初始化流程的完整性
    /// </summary>
    private void TestInitializationCompleteness()
    {
        try
        {
            AddLog("测试4: 初始化流程的完整性");

            AddLog("🔍 验证初始化流程的各个步骤是否都执行了");

            // 验证1: 通知器是否设置
            AddLog("   检查通知器设置...");
            // 这个无法直接验证，但可以通过后续的通知行为来间接验证

            // 验证2: 监控是否可以启动
            AddLog("   检查监控功能...");
            try
            {
                // 使用公开的监控方法
                bool monitorResult = LicenseManager.StartLicenseMonitoring(null!);
                AddLog($"   监控启动: {(monitorResult ? "✅ 成功" : "❌ 失败")}");
            }
            catch (Exception ex)
            {
                AddLog($"   监控测试异常: {ex.Message}");
            }

            // 验证3: 授权状态检查是否正常
            AddLog("   检查授权状态功能...");
            try
            {
                var status = LicenseManager.GetCurrentStatus();
                AddLog($"   状态获取: ✅ 成功 - {status.Message}");
            }
            catch (Exception ex)
            {
                AddLog($"   状态获取: ❌ 失败 - {ex.Message}");
            }

            // 验证4: 基本API是否正常
            AddLog("   检查基本API功能...");
            try
            {
                var isValid = LicenseManager.IsLicenseValid();
                var licenseInfo = LicenseManager.GetLicenseInfo();
                AddLog($"   API调用: ✅ 正常");
                AddLog($"   授权有效: {isValid}");
                AddLog($"   授权信息: {(licenseInfo != null ? "有" : "无")}");
            }
            catch (Exception ex)
            {
                AddLog($"   API调用: ❌ 异常 - {ex.Message}");
            }

            AddLog("✅ 初始化流程完整性测试完成");

            // 总结
            AddLog("📋 测试总结:");
            AddLog("   ✅ 初始化流程不会因授权问题而中断");
            AddLog("   ✅ 授权验证失败时仍完成初始化");
            AddLog("   ✅ 监控和状态检查功能正常");
            AddLog("   ✅ 错误提示通过非阻塞对话框显示");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 初始化流程完整性测试失败: {ex.Message}");
        }
    }

    #endregion

    #region 后台注册测试功能

    /// <summary>
    /// 测试后台注册按钮点击事件
    /// </summary>
    private void BtnTestBackgroundRegistration_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            AddLog("=== 开始测试后台注册功能 ===");

            // 测试1: 基本后台注册（不允许重复注册）
            TestBasicBackgroundRegistration();

            // 测试2: 允许重复注册的后台注册
            TestDuplicateAllowedBackgroundRegistration();

            // 测试3: 错误处理测试
            TestBackgroundRegistrationErrorHandling();

            // 测试4: 与现有UI注册的对比
            TestBackgroundVsUIRegistration();

            AddLog("=== 后台注册功能测试完成 ===");

            MessageBox.Show("后台注册功能测试完成！请查看日志了解详细结果。", "测试完成",
                          MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            AddLog($"后台注册功能测试失败: {ex.Message}");
            MessageBox.Show($"后台注册功能测试失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 测试基本后台注册（不允许重复注册）
    /// </summary>
    private void TestBasicBackgroundRegistration()
    {
        try
        {
            AddLog("测试1: 基本后台注册（不允许重复注册）");

            // 获取当前授权码（如果有的话）
            var currentLicenseCode = GetCurrentLicenseCodeForTest();

            if (!string.IsNullOrEmpty(currentLicenseCode))
            {
                AddLog($"📋 当前已有授权码: {currentLicenseCode.Substring(0, Math.Min(20, currentLicenseCode.Length))}...");

                // 测试重复注册相同授权码（应该被拒绝）
                AddLog("🔍 测试重复注册相同授权码（应该被拒绝）");
                var result1 = LicenseManager.RegisterLicenseBackground(currentLicenseCode, allowDuplicateRegistration: false);

                AddLog($"   结果: {(result1.Success ? "✅ 成功" : "❌ 失败")}");
                AddLog($"   消息: {result1.Message}");
                AddLog($"   错误类型: {result1.ErrorType}");
                AddLog($"   风险级别: {result1.RiskLevel}");

                if (!result1.Success && result1.ErrorType == LicenseRegistrationErrorType.DuplicateRegistration)
                {
                    AddLog("✅ 重复注册检测正常工作");
                }
                else
                {
                    AddLog("⚠️ 重复注册检测可能有问题");
                }
            }
            else
            {
                AddLog("📋 当前无授权码，跳过重复注册测试");
            }

            // 测试无效授权码
            AddLog("🔍 测试无效授权码");
            var result2 = LicenseManager.RegisterLicenseBackground("INVALID_LICENSE_CODE", allowDuplicateRegistration: false);

            AddLog($"   结果: {(result2.Success ? "✅ 成功" : "❌ 失败")}");
            AddLog($"   消息: {result2.Message}");
            AddLog($"   错误类型: {result2.ErrorType}");

            // 测试空授权码
            AddLog("🔍 测试空授权码");
            var result3 = LicenseManager.RegisterLicenseBackground("", allowDuplicateRegistration: false);

            AddLog($"   结果: {(result3.Success ? "✅ 成功" : "❌ 失败")}");
            AddLog($"   消息: {result3.Message}");
            AddLog($"   错误类型: {result3.ErrorType}");

            if (result3.ErrorType == LicenseRegistrationErrorType.InvalidInput)
            {
                AddLog("✅ 输入验证正常工作");
            }

            AddLog("✅ 基本后台注册测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 基本后台注册测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试允许重复注册的后台注册
    /// </summary>
    private void TestDuplicateAllowedBackgroundRegistration()
    {
        try
        {
            AddLog("测试2: 允许重复注册的后台注册");

            var currentLicenseCode = GetCurrentLicenseCodeForTest();

            if (!string.IsNullOrEmpty(currentLicenseCode))
            {
                AddLog($"📋 使用当前授权码进行重复注册测试");

                // 测试允许重复注册相同授权码
                AddLog("🔍 测试允许重复注册相同授权码");
                var result = LicenseManager.RegisterLicenseBackground(currentLicenseCode, allowDuplicateRegistration: true);

                AddLog($"   结果: {(result.Success ? "✅ 成功" : "❌ 失败")}");
                AddLog($"   消息: {result.Message}");
                AddLog($"   错误类型: {result.ErrorType}");
                AddLog($"   风险级别: {result.RiskLevel}");

                if (result.Success)
                {
                    AddLog("✅ 允许重复注册功能正常工作");
                    AddLog("⚠️ 注意：时间记录可能已被重置");

                    // 刷新状态显示
                    RefreshStatus();
                }
                else
                {
                    AddLog("⚠️ 允许重复注册功能可能有问题");
                }
            }
            else
            {
                AddLog("📋 当前无授权码，跳过重复注册测试");

                // 可以提示用户先注册一个授权码
                var testResult = MessageBox.Show("当前无授权码，是否要先打开注册对话框注册一个授权码进行测试？",
                                               "测试提示", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (testResult == MessageBoxResult.Yes)
                {
                    var dialog = new LicenseApp.Client.LicenseRegistrationDialog("后台注册测试", this);
                    dialog.ShowDialog();

                    // 重新获取授权码
                    currentLicenseCode = GetCurrentLicenseCodeForTest();
                    if (!string.IsNullOrEmpty(currentLicenseCode))
                    {
                        AddLog("📋 已注册授权码，继续测试");
                        TestDuplicateAllowedBackgroundRegistration(); // 递归调用
                        return;
                    }
                }
            }

            AddLog("✅ 允许重复注册测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 允许重复注册测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试后台注册错误处理
    /// </summary>
    private void TestBackgroundRegistrationErrorHandling()
    {
        try
        {
            AddLog("测试3: 后台注册错误处理");

            // 测试各种错误情况
            var testCases = new[]
            {
                new { Name = "空字符串", Code = (string?)"", ExpectedError = LicenseRegistrationErrorType.InvalidInput },
                new { Name = "null值", Code = (string?)null, ExpectedError = LicenseRegistrationErrorType.InvalidInput },
                new { Name = "纯空格", Code = (string?)"   ", ExpectedError = LicenseRegistrationErrorType.InvalidInput },
                new { Name = "无效格式", Code = (string?)"INVALID_FORMAT", ExpectedError = LicenseRegistrationErrorType.RegistrationFailed },
                new { Name = "错误JSON", Code = (string?)"{invalid json}", ExpectedError = LicenseRegistrationErrorType.RegistrationFailed }
            };

            foreach (var testCase in testCases)
            {
                AddLog($"🔍 测试错误情况: {testCase.Name}");

                try
                {
                    var result = LicenseManager.RegisterLicenseBackground(testCase.Code!, allowDuplicateRegistration: false);

                    AddLog($"   结果: {(result.Success ? "✅ 成功" : "❌ 失败")}");
                    AddLog($"   错误类型: {result.ErrorType}");
                    AddLog($"   消息: {result.Message}");

                    if (!result.Success && result.ErrorType == testCase.ExpectedError)
                    {
                        AddLog($"   ✅ 错误处理正确");
                    }
                    else if (result.Success)
                    {
                        AddLog($"   ⚠️ 预期失败但成功了");
                    }
                    else
                    {
                        AddLog($"   ⚠️ 错误类型不匹配，预期: {testCase.ExpectedError}，实际: {result.ErrorType}");
                    }
                }
                catch (Exception ex)
                {
                    AddLog($"   ❌ 异常: {ex.Message}");
                }
            }

            AddLog("✅ 错误处理测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 错误处理测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试后台注册与UI注册的对比
    /// </summary>
    private void TestBackgroundVsUIRegistration()
    {
        try
        {
            AddLog("测试4: 后台注册与UI注册的对比");

            AddLog("📊 功能对比:");
            AddLog("   后台注册 vs UI注册");
            AddLog("   ✅ 无用户交互 vs ❌ 需要用户输入");
            AddLog("   ✅ 参数控制重复注册 vs ❌ 对话框确认");
            AddLog("   ✅ 结构化返回结果 vs ❌ 简单成功/失败");
            AddLog("   ✅ 适合自动化 vs ❌ 适合手动操作");

            AddLog("🔧 API对比:");
            AddLog("   后台注册: LicenseManager.RegisterLicenseBackground(code, allowDuplicate)");
            AddLog("   UI注册: LicenseManager.RegisterLicense(code) + 对话框交互");

            AddLog("📋 使用场景:");
            AddLog("   后台注册: 预先隐藏的授权码、自动化部署、批量注册");
            AddLog("   UI注册: 用户手动输入授权码、交互式注册");

            // 测试API兼容性
            AddLog("🔍 测试API兼容性");

            try
            {
                // 确保新方法不影响现有功能
                var isValid = LicenseManager.IsLicenseValid();
                var licenseInfo = LicenseManager.GetLicenseInfo();
                var status = LicenseManager.GetCurrentStatus();

                AddLog("   ✅ 现有API正常工作");
                AddLog($"   📊 当前状态: {status.Message}");
            }
            catch (Exception ex)
            {
                AddLog($"   ❌ API兼容性问题: {ex.Message}");
            }

            AddLog("✅ 对比测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 对比测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取当前授权码用于测试（如果存在）
    /// </summary>
    private string GetCurrentLicenseCodeForTest()
    {
        try
        {
            // 尝试从UnifiedLicenseGuard加载当前授权码
            // 注意：这是为了测试目的，实际应用中不应该暴露授权码
            var licenseInfo = LicenseManager.GetLicenseInfo();
            if (licenseInfo != null)
            {
                // 如果有授权信息，说明有授权码，但我们无法直接获取原始授权码
                // 这里返回一个标识，表示存在授权码
                return "EXISTING_LICENSE_CODE"; // 占位符，表示存在授权码
            }

            return "";
        }
        catch
        {
            return "";
        }
    }

    #endregion

    #region 一键集成测试功能

    /// <summary>
    /// 测试一键集成按钮点击事件
    /// </summary>
    private void BtnTestIntegration_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            AddLog("=== 开始测试一键集成方案 ===");

            // 测试1: 授权注册对话框
            TestLicenseRegistrationDialog();

            // 测试2: 授权管理控件
            //TestLicenseManagementControl();

            // 测试3: API调用
            TestLicenseManagerAPI();

            AddLog("=== 一键集成测试完成 ===");

            //MessageBox.Show("一键集成测试完成！请查看日志了解详细结果。", "测试完成",
            //              MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            AddLog($"一键集成测试失败: {ex.Message}");
            MessageBox.Show($"一键集成测试失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 测试授权注册对话框
    /// </summary>
    private void TestLicenseRegistrationDialog()
    {
        try
        {
            AddLog("测试1: 授权注册对话框");

            // 创建并显示授权注册对话框
            var dialog = new LicenseApp.Client.LicenseRegistrationDialog("测试一键集成方案", this);

            AddLog("✅ 授权注册对话框创建成功");
            AddLog("📋 对话框包含以下功能:");
            AddLog("   - 公钥状态检查");
            AddLog("   - 机器码显示和复制");
            AddLog("   - 授权码输入和注册");
            AddLog("   - 现有授权信息显示");

            // 显示对话框（非阻塞方式）
            var result = MessageBox.Show("是否要打开授权注册对话框进行测试？", "测试确认",
                                       MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                dialog.ShowDialog();
                AddLog("✅ 授权注册对话框测试完成");
            }
            else
            {
                AddLog("⏭️ 跳过授权注册对话框显示测试");
            }
        }
        catch (Exception ex)
        {
            AddLog($"❌ 授权注册对话框测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 测试授权管理控件
    /// </summary>
    private void TestLicenseManagementControl()
    {
        try
        {
            AddLog("测试2: 授权管理控件");

            // 创建授权管理控件
            var control = new LicenseApp.Client.Controls.LicenseManagementControl();

            AddLog("✅ 授权管理控件创建成功");
            AddLog("📋 控件包含以下功能:");
            AddLog("   - 公钥管理");
            AddLog("   - 机器码信息显示");
            AddLog("   - 授权注册");
            AddLog("   - 授权状态显示");

            // 测试控件的公开方法
            var machineCode = control.GetMachineCode();
            AddLog($"🔧 控件机器码获取: {(!string.IsNullOrEmpty(machineCode) ? "成功" : "失败")}");

            var licenseInfo = control.GetLicenseInfo();
            AddLog($"📄 控件授权信息获取: {(licenseInfo != null ? "有授权" : "无授权")}");

            var status = control.GetCurrentStatus();
            AddLog($"📊 控件状态获取: {status.Message}");

            // 显示控件测试窗口
            var testResult = MessageBox.Show("是否要打开授权管理控件测试窗口？", "测试确认",
                                           MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (testResult == MessageBoxResult.Yes)
            {
                ShowLicenseManagementControlWindow(control);
                AddLog("✅ 授权管理控件测试完成");
            }
            else
            {
                AddLog("⏭️ 跳过授权管理控件显示测试");
            }
        }
        catch (Exception ex)
        {
            AddLog($"❌ 授权管理控件测试失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 显示授权管理控件测试窗口
    /// </summary>
    private void ShowLicenseManagementControlWindow(LicenseApp.Client.Controls.LicenseManagementControl control)
    {
        var window = new Window
        {
            Title = "授权管理控件测试",
            Width = 600,
            Height = 500,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            Owner = this,
            Content = control
        };

        window.ShowDialog();
    }

    /// <summary>
    /// 测试授权管理器API
    /// </summary>
    private void TestLicenseManagerAPI()
    {
        try
        {
            AddLog("测试3: 授权管理器API");

            // 测试基本API
            var isValid = LicenseApp.Client.LicenseManager.IsLicenseValid();
            AddLog($"🔍 IsLicenseValid(): {isValid}");

            var licenseInfo = LicenseApp.Client.LicenseManager.GetLicenseInfo();
            if (licenseInfo != null)
            {
                AddLog($"📄 授权信息:");
                AddLog($"   - 生效日期: {licenseInfo.StartDate:yyyy-MM-dd}");
                AddLog($"   - 到期日期: {licenseInfo.EndDate:yyyy-MM-dd}");
                AddLog($"   - 授权天数: {licenseInfo.Days}");
                AddLog($"   - AGV数量: {licenseInfo.AgvCount}");
                AddLog($"   - 机器码: {licenseInfo.MachineCode ?? "未绑定"}");
            }
            else
            {
                AddLog("📄 当前无有效授权");
            }

            var status = LicenseApp.Client.LicenseManager.GetCurrentStatus();
            AddLog($"📊 当前状态: {status.Message}");
            AddLog($"🎨 状态级别: {status.Status}");

            // 测试机器码生成
            var machineCode = LicenseApp.Client.MachineCodeGenerator.GenerateMachineCode();
            AddLog($"🔧 当前机器码: {machineCode}");

            AddLog("✅ 授权管理器API测试完成");
        }
        catch (Exception ex)
        {
            AddLog($"❌ 授权管理器API测试失败: {ex.Message}");
        }
    }

    #endregion
}